package com.cetsk.android.talkorigins;

import com.cetsk.android.talkorigins.Claim;

import android.content.Intent;
import android.database.SQLException;
import android.database.sqlite.SQLiteStatement;
import android.os.Bundle;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.app.ListFragment;
import android.util.Log;
import android.view.ContextMenu;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ContextMenu.ContextMenuInfo;
import android.webkit.WebView;
import android.widget.AdapterView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.Toast;

public class ClaimListFragment extends ListFragment {
	boolean mDualPane;
	private Claim claim;

	public ClaimListFragment() {
	}

	public ClaimListFragment(Claim c) {
		this.claim = c;
	}
	
	@Override
	public void onViewCreated(View view, Bundle savedInstanceState) {
	    super.onViewCreated(view, savedInstanceState);
	    registerForContextMenu(getListView());
	}

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);

		View claimViewFragment = getActivity().findViewById(
				R.id.claim_view_fragment);
		mDualPane = claimViewFragment != null
				&& claimViewFragment.getVisibility() == View.VISIBLE;

		int claimId = 0;
		if (claim != null) {
			claimId = claim.getId();
		}
		Log.d("CLAIMID", claimId + "");
		setListAdapter(new ClaimAdapter(getActivity().getBaseContext(),
				R.layout.list_item, ClaimHelper.getClaims(getActivity(),
						claimId, true)));

	}

	@Override
	public void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState(outState);
	}

	@Override
	public void onListItemClick(ListView l, View v, int position, long id) {
		final Claim claim = (Claim) ((LinearLayout) v).getTag();
		if (claim.getChildren().size() != 0) {
			showChildren(claim);
			if (!mDualPane)
				return;
		}
		if (claim.getUrl() != null && !claim.getUrl().isEmpty()) {
			showDetails(claim);
		}

	}

	@Override
	public void onCreateContextMenu(ContextMenu menu, View v,
			ContextMenuInfo menuInfo) {
		AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) menuInfo;
		menu.setHeaderTitle("Action");
		int i = 0;
		Claim c = (Claim) info.targetView.getTag();
		try {
			if (c.getChildren().size() > 0) {
				menu.add(Menu.NONE, 1, ++i, "View Children");
			}
			if (c.getUrl().length() > 1) {
				menu.add(Menu.NONE, 1, ++i, "View Claim");
				menu.add(Menu.NONE, 1, ++i, "Add as Favorite");
				menu.add(Menu.NONE, 1, ++i, "Share");
			}
		} catch (Exception e) {
			Log.e("Problem parsing claim", e.toString());
		}
	}
	
	public boolean onContextItemSelected(MenuItem item) {
	    AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo)item.getMenuInfo();
		Claim c = (Claim) info.targetView.getTag();
		
		if(item.toString().equals("View Claim")){
			showDetails(c);
		} else if(item.toString().equals("View Children")) {
			showChildren(c);
		} else if(item.toString().equals("Add as Favorite")) {
			DatabaseHelper dbh = new DatabaseHelper(getActivity().getApplicationContext());
			//SQLiteDatabase dbh = this.openOrCreateDatabase(DatabaseHelper.DBNAME, SQLiteDatabase.OPEN_READWRITE, null);
			try {
				SQLiteStatement stmt = dbh.getWritableDatabase().compileStatement("INSERT INTO " + DatabaseHelper.FAVORITES_TABLE + " (Id,ClaimId) VALUES (null,?)");
				stmt.bindLong(1, c.getId());
				stmt.execute();
				Toast.makeText(getActivity().getApplicationContext(), "Favorite Added", Toast.LENGTH_SHORT).show();
			} catch (SQLException sqle){
				if(sqle.getMessage().startsWith("error code 19:")){
					Toast.makeText(getActivity().getApplicationContext(), "Could not add favorite, because it already exists!", Toast.LENGTH_SHORT).show();
				} else {
					Toast.makeText(getActivity().getApplicationContext(), "Error adding favorite: "+sqle.getMessage(), Toast.LENGTH_SHORT).show();
				}
				Log.e("SQLError",sqle.getMessage());
			} finally {
				dbh.close();
			}
		} else if(item.toString().equals("Share")){
				String url = "http://www.talkorigins.org/indexcc/" + c.getUrl();
				Intent shareIntent = new Intent(android.content.Intent.ACTION_SEND);
				shareIntent.setType("text/plain");
				shareIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, "TalkOrigins article: " + c.getName());
				shareIntent.putExtra(android.content.Intent.EXTRA_TEXT, url);

				startActivity(Intent.createChooser(shareIntent, "Share via..."));
		} else {
			
		}
    	return true;
    }

	void showChildren(final Claim claim) {
		ClaimListFragment cf = new ClaimListFragment(claim);
		FragmentTransaction transaction = getFragmentManager()
				.beginTransaction();
		transaction.replace(R.id.claim_list_fragment, cf);
		transaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
		transaction.addToBackStack(null);
		transaction.commit();
	}

	void showDetails(final Claim claim) {
		Log.i("CLAIM_URL", claim.getUrl());
		try {
			if (mDualPane) {
				final WebView wv = (WebView) getActivity().findViewById(
						R.id.webview);
				if (wv != null) {
					new Thread() {
						public void run() {
							try {
								String html = null;
								HTMLParse hp = new HTMLParse(getActivity()
										.getApplicationContext());
								html = hp
										.getHtml("http://www.talkorigins.org/indexcc/"
												+ claim.getUrl());
								html = html.replaceAll("\\.\\./",
										"http://talkorigins.org/indexcc/");
								if (html != null && html.length() > 0) {
									wv.loadData(html, "text/html", "utf-8");
								} else {
									Toast
											.makeText(
													getActivity()
															.getApplicationContext(),
													"There was a problem fetching HTML.",
													Toast.LENGTH_SHORT).show();
									Log.i("HTML_ERROR", "Could not Parse");
								}
							} catch (Exception e) {
							}
						}
					}.start();
				}
			} else {
				Intent intent = new Intent(getActivity()
						.getApplicationContext(), ClaimViewActivity.class);
				intent.putExtra("claim", claim);
				startActivity(intent);
			}
		} catch (Exception e) {
			e.printStackTrace();
			Log.e("ERROR", e.getMessage());
		}
	}
}